package org.example.activiti.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 使用activiti-spring-boot-starter(即Activiti7)坐标依赖后，默认集成了SpringSecurity安全框架，因此我们需要新增SpringSecurity相关配置。
 * <p>
 * 内存用户模拟：为了方便测试，官方在GitHub上给出了例子，我们也完全可以采用这种方式，因为只是测试，没必要完善用户信息获取的代码（用户信息存储在数据库），
 * 新增一个UserDetailsServiceConfiguration（名字可以随便取）配置类.
 * 如果不集成，会报错
 */
@Configuration
@Slf4j
public class UserDetailsServiceConfiguration {


    @Bean
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
        String[][] usersGroupsAndRoles = {{"system", "password", "ROLE_ACTIVITY_USER"}, {"admin", "password", "ROLE_ACTIVITY_ADMIN"}};
        for (String[] user : usersGroupsAndRoles) {
            List<String> authoritiesStrings = Arrays.asList(Arrays.copyOfRange(user, 2, user.length));
            log.info("> Registering new user: " + user[0] + " with the following Authorities[" + authoritiesStrings + "]");
            inMemoryUserDetailsManager.createUser(new User(user[0], passwordEncoder().encode(user[1]),
                    authoritiesStrings.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList())));
        }
        return inMemoryUserDetailsManager;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
